<template>
  <div class="content_wrap" :class="{ 'show-more-open': showMore }">
    <div class="mainManage">
      <iu-header>
        <template #left>
          <img src="../../styles/logo.svg" alt="" style="width:40px" />
          <span>设备管理</span>
        </template>
        <template #title></template>
        <template #right>
         <div v-focusable  @click="backToHomepage">
          <iconSvg name="home" w="20px" h="22px" class="right_icon"></iconSvg>
        </div>
        </template>
      </iu-header>
      <Application> </Application>
      <div class="showPie" :class="{ show: showPie }">
        <div class="show-title">
          <div class="fixed_dep_box">
            <div class="btn_box">
              <div
                class="department_select"
                :class="showTree ? 'active' : ''"
                @click="showTreeFn(true)"
              >
                <p class="department_name">
                  {{ curDepartment.departmentName }}
                </p>
                <iconSvg
                  name="downFill"
                  w="23px"
                  height="13px"
                  class="selece_icon"
                  ref="selece_icon"
                ></iconSvg>
              </div>
              <transition name="slide">
                <div class="dep_box" v-show="showTree">
                  <dep-tree
                    ref="depTree"
                    @changeId="change"
                    @showTreeFn="showTreeFn"
                    @initCurDepartment="initCurDepartment"
                    :initDepartment="curDepartment"
                  ></dep-tree>
                </div>
              </transition>
            </div>
            <div
              v-if="showTree"
              @click="showTreeFn(false)"
              style="position: fixed;top: 0;left:0; width: 100vw;height: 100vh; z-index: 9"
            ></div>
          </div>
          <div class="show-btn" @click="showPie = false" v-if="showPie">
            <span>收起</span>
            <x-icon type="ios-arrow-down" size="18" fill="#fff"></x-icon>
          </div>
          <div class="show-btn" v-else-if="!showPie" @click="showPie = true">
            <span>展开</span>
            <x-icon type="ios-arrow-up" size="18" fill="#fff"></x-icon>
          </div>
        </div>
        <div
          v-show="showPie"
          style="color:#fff;font-size:16px;margin-left:16px;margin-top:6px"
        >
          设备运行状态
        </div>
        <div
          v-show="showPie"
          id="myPieChart"
          style="width: 100vw; height: 260px;"
        ></div>
      </div>
      <div class="nav-tab" v-if="privilege('wechat_manage', 'wechat_manage:pop:record')">
        <div
          :class="{ 'tab-active': navIndex === index }"
          @click="handleNav(index)"
          v-for="(item, index) in ['运行状态', '出库台账']"
          :key="index"
        >
          {{ item }}
        </div>
      </div>
      <device-list
        v-if="navIndex === 0"
        :navIndex="navIndex"
        :curDepartment="curDepartment"
        @drawLine="drawLine"
        @eventOpenNext="eventOpenNext"
      ></device-list>
      <outbound-list
        v-if="navIndex === 1"
        :navIndex="navIndex"
        :curDepartment="curDepartment"
        @eventOpenNext="eventOpenNext"
      ></outbound-list>
    </div>
  </div>
</template>
<script>
import { Tab, TabItem } from "vux";
import depTree from "@/components/common/tree";
import iuCard from "@/components/common/card/index";
import iuHeader from "@/components/common/header/index";
import deviceList from "@/components/pages/device_manage/deviceList";
import outboundList from "@/components/pages/replace/outboundList";
import Application from "@/components/common/application";
import DeviceDao from "@/daos/device_dao";
import { Privilege } from "@/mixin";

let _this = null;
export default {
  components: {
    Tab,
    TabItem,
    depTree,
    iuCard,
    iuHeader,
    deviceList,
    outboundList,
    Application,
  },
  data() {
    return {
      isAndriod: false,
      showPie: false,
      showMore: false,
      showTree: false,
      showMoreBtn: false,
      navIndex: 0,
      statusIndex: 2,
      filterCache: {},
      curDepartment: {
        departmentName: "全企业",
        id: ""
      },
      search: {
        departmentId: "",
        deviceName: "",
        deviceCode: "",
        changeStatus: ""
      },
      // ['全部', '未监控','运转', '停止', '故障', '离线']

      deviceStatus: ["全部", "未监控", "运转", "停止", "故障", "离线"],
      pageSize: 10,
      pageNum: 1,
      deviceInfo: [],
      deviceNum: "",
      componentNum: "",
      produceNum: 0,
      radio: "",
      userActionMap: {},
      orgNumList: [],
      deviceData: [],
      url: "",
      localUrl: ""
    };
  },
  computed: {
    user() {
      return this.$store.state.user;
    }
  },
  mixins: [Privilege],
  created() {
    _this = this;

    if (!this.user) {
      this.getUser();
    } else {
      this.init();
    }
  },
  mounted() {
    window.addEventListener("popstate", this.backToDep, false);
  },
  beforeDestroy() {
    window.removeEventListener("popstate", this.backToDep, false);
  },
  //返回首页的公共方法
  inject: ["backToHomepage",'backToG6page'],
  methods: {
    getUser() {
      this.$http(this.$API.getUserInfo, {})
        .then(res => {
          if (res) {
            this.$store.commit("saveUser", res);
            this.init();
          }
        })
        .catch(e => {});
    },
    backToDep() {
      this.$nextTick(e => {
        let node = this.$refs.depTree.treeFind(
          [this.user.serviceAreaTree],
          e => e.id === this.curDepartment.id
        );
        let parent = this.$refs.depTree.treeFind(
          [this.user.serviceAreaTree],
          e => e.id === node.parentId
        );
        if (parent) {
          this.$refs.depTree.change(parent.id, parent.departmentName);
        }
      });
    },
    init() {
      let filterCache = this.$store.state.filterCache;
      if (filterCache.curDepartment) {
        if (
          filterCache.curDepartment &&
          this.user.serviceArea.includes(+filterCache.curDepartment.id)
        ) {
          this.curDepartment = filterCache.curDepartment;
        }
      }
      if (!this.curDepartment.id) {
        if (!this.user) {
          this.$http(this.$API.getUserInfo, {}, true).then(res => {
            this.userId = res.id;
            if (res) {
              this.$store.commit("saveUser", res);
              this.curDepartment.id = this.user.serviceAreaTree.id;
              this.curDepartment.departmentName = this.user.serviceAreaTree.departmentName;
            }
          });
        } else {
          this.userId = this.user.id;
          this.curDepartment.id = this.user.serviceAreaTree.id;
          this.curDepartment.departmentName = this.user.serviceAreaTree.departmentName;
        }
      }
      // this.getDeviceNum();
      // this.getDeviceList();
      this.getDomin();
      _this.localUrl = location.href.split("#")[0];
      // 获取微信签名
      this.$http(
        this.$API.getWxSign,
        {
          url: encodeURIComponent(_this.localUrl)
        },
        true
      )
        .then(res => {
          if (res) {
            wx.config({
              debug: false,
              appId: res.appId, // 必填,公众号的唯一标识
              timestamp: res.timestamp, // 必填,生成签名的时间戳
              nonceStr: res.nonceStr, // 必填,生成签名的随机串
              signature: res.signature, // 必填,签名
              jsApiList: ["scanQRCode"] // 必填,需要使用的JS接口列表
            });
            /* 处理失败验证 */
            wx.error(function(res) {
              console.log("res:====>", res);
              // config 信息验证失败会执行error函数,如签名过期导致验证失败,具体错误信息可以打开config的debug模式查看,也可以在返回的res参数中查看,对于SPA可以在这里更新签名
            });
          }
        })
        .catch(e => {});
    },
    change(id, departmentName) {
      this.curDepartment = {
        departmentName,
        id: id
      };
      let filterCache = {};
      filterCache.curDepartment = this.curDepartment;
      // localStorage.setItem("filterCache", JSON.stringify(filterCache));
      this.$store.commit("setFilterCache", filterCache);
      // console.log(id, name,1);
      // if (this.navIndex === 0) {
      //   this.getDeviceList();
      //   this.getDeviceNum();
      // }
    },
    handleNav(index) {
      this.navIndex = index;
    },
    initCurDepartment(id, departmentName) {
      // console.log(id, name);
      this.curDepartment = {
        departmentName,
        id: id
      };
    },
    getMore(page, mescroll) {
      // this.pageNum = page.num;
      this.pageNum++;
      this.getDeviceList();
    },
    //跳转到全部设备
    toStatusDevice(item) {
      this.statusIndex = item.key;
      this.pageNum = 1;
      this.getDeviceList();
      this.getDeviceNum();
    },
    eventOpenNext(item) {
      history.pushState(null, null, location.hash);
      this.$refs.depTree.change(item.departmentId, item.departmentName);
    },
    getDeviceOrgNumList() {
      let params = {
        departmentId: this.curDepartment.id
      };
      DeviceDao.getDeviceOrgNumList(params, res => {
        this.orgNumList = res;
      });
    },
    getDeviceList() {
      // ['全部', '未监控','运转', '停止', '故障', '离线']
      let params = {
        orgId: this.user.org.id,
        deviceName: this.search.deviceName,
        deviceCode: this.search.deviceCode,
        departmentId: this.curDepartment.id,
        runStatus: this.statusIndex,
        pageNum: this.pageNum,
        pageSize: this.pageSize
      };
      DeviceDao.getDeviceList(params, res => {
        if (res) {
          if (this.pageNum === 1) {
            this.deviceData.splice(0, this.deviceData.length);
          }
          this.showMoreBtn = !(
            !res.totalPages || this.pageNum === res.totalPages
          );
          this.deviceData.push(...res.content);
        }
      });
    },
    showTreeFn(status) {
      if (status) {
        this.$refs.selece_icon.$el.style.transform = "rotate(-180deg)";
      } else {
        this.$refs.selece_icon.$el.style.transform = "rotate(0deg)";
      }
      this.showTree = status;
    },
    deviceDetails(item) {
      // localStorage.setItem("deviceInfo", JSON.stringify(item));
      this.$router.push({
        name: "deviceInfos",
        query: {
          deviceId: item.deviceId
        }
      });
    },
    // 画图
    // run:运行,abnormal:异常,moduleAbnormal:模块异常,noneNum:无,stopNum:停止运转
    drawLine(deviceInfo, radio) {
      let run = deviceInfo[1].deviceNum,
        abnormal = deviceInfo[3].deviceNum,
        moduleAbnormal = deviceInfo[4].deviceNum,
        noneNum = deviceInfo[0].deviceNum,
        stopNum = deviceInfo[2].deviceNum;
      let myPieChart = this.$echarts.init(
        document.getElementById("myPieChart")
      );
      myPieChart.setOption({
        color: ["#456de6", "#d81e06", "#d98807", "#45a3e6", "#45d8e6"], //配置颜色
        tooltip: {
          trigger: "item",
          formatter: "{b}: {c} ({d}%)"
        },
        graphic: [
          {
            type: "text",
            left: "center",
            top: "40%",
            style: {
              text: radio + "%\n",
              fill: "#fff",
              fontSize: 20,
              fontWeight: 500
            }
          },
          {
            type: "text",
            left: "center",
            top: "50%",
            style: {
              text: "运行",
              fill: "#fff",
              fontSize: 18
            }
          }
        ],
        series: [
          {
            // name:'',
            type: "pie",
            radius: ["50%", "70%"],
            avoidLabelOverlap: false,
            bottom: 16,
            label: {
              normal: {
                show: false,
                position: "inner"
              },
              emphasis: {
                show: true,
                textStyle: {
                  fontSize: "14",
                  fontWeight: "bold"
                }
              }
            },
            labelLine: {
              normal: {
                show: true
              }
            },
            data: [
              {
                value: run,
                name: "运行"
              },
              {
                value: abnormal,
                name: "故障"
              },
              {
                value: moduleAbnormal,
                name: "离线"
              },
              {
                value: noneNum,
                name: "未监控"
              },
              {
                value: stopNum,
                name: "停止"
              }
            ]
          }
        ]
      });
    },
    getDomin() {
      this.url = window.location.protocol + "//" + window.location.host;
    }
  }
};
</script>
<style lang="less" scoped>
.fade-enter-active,
.fade-leave-active {
  transform: translateY(0);
}
.fade-enter,
.fade-leave-to {
  transform: translateY(-140%);
}
.content_wrap {
  background: #22233f;
  height: 100vh;
  width: 100%;

  &.show-more-open {
    overflow: hidden;
  }
  // position: fixed;
  .showPie {
    margin: 0 auto;
    padding: 8px 0;
    width: 100%;
    background-color: #18182c;
    &.show {
      height: auto;
    }

    // div {
    // background-color: unset !important;
    // }
    .show-title {
      // color: #fff;
      display: flex;
      justify-content: space-between;
      align-items: center;
      font-size: 16px;
      padding: 0 16px;
      .show-btn {
        color: #fff;
        font-size: 12px;
        display: flex;
        align-items: center;
      }
    }
  }
  .nav-tab {
    display: flex;
    align-items: center;
    background-color: #18182c;
    > div {
      flex: 1;
      padding: 16px;
      text-align: center;
      font-size: 16px;
      color: #fff;
      &.tab-active {
        color: rgb(69, 109, 230);
      }
    }
  }
  .grayDiv {
    background: #18182c;
    height: 100%;
  }

  .footerButton {
    height: auto;
    // width: 100%;
    color: #ffffff;
    padding: 0 16px;
    background-color: #292a4d;
  }

  .scroll-wrapper {
    // width: 90%;
    white-space: nowrap;
    overflow: hidden;
    color: #fff;
  }
  .deviceOrg {
    height: 100%;
    padding: 12px 16px 32px;
    background-color: #22233f;
    .device-card {
      margin-bottom: 12px;
      .device-code {
        margin-left: 6px;
        color: rgba(255, 255, 255, 0.6);
      }
      .device-card-body {
        display: flex;
        flex-wrap: wrap;
        .body-item {
          flex: none;
          font-size: 14px;
          margin: 3px 0;
          width: 65%;
          &:nth-child(2n) {
            width: 35%;
          }
          .body-item-key {
            display: flex;
            align-items: center;
            // color: gray;
            .device-status {
              position: relative;
              margin-left: 16px;
              color: rgba(255, 255, 255, 0.6);
              &::before {
                content: "";
                position: absolute;
                left: -12px;
                top: 7px;
                width: 8px;
                height: 8px;
                border-radius: 4px;
                background-color: #fff;
              }
            }
            .status1::before {
              background-color: gray;
            }
            .status2::before {
              background-color: #456de5;
            }
            .status3::before {
              background-color: #dc9610;
            }
            .status4::before {
              background-color: #dd6031;
            }
            .status5::before {
              background-color: #d2d2d2;
            }
            span {
              margin-left: 4px;
            }
          }
          // .body-item-value {
          // }
        }
      }
    }

    .newpage_work_more {
      height: 40px;
      font-size: 12px;
      line-height: 40px;
      text-align: center;
      color: #456de6;
    }
    .not-content {
      width: 100%;
      display: flex;
      justify-content: center;
      align-items: center;
      flex-direction: column;
      margin-top: 40px;
      text-align: center;
      img {
        width: 64px;
        height: 64px;
        margin-left: 20px;
      }
      .title {
        margin: 8px auto;
        width: 126px;
        height: 40px;
        font-size: 14px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: rgba(158, 198, 251, 1);
        line-height: 20px;
        text-align: center;
      }
    }
  }
}

.fixed_dep_box {
  // padding: 5px 0;
  background: #22233f;
  width: 80%;
  .btn_box {
    display: flex;
    // padding: 0 16px;
    justify-content: space-between;
    position: relative;
    height: 28px;
    .department_select {
      position: relative;
      width: 100%;
      border-radius: 2px;
      background: #292a4d;
      transition: background 0.3s ease-in-out;
      &.active {
        background: #383a69;
      }
      .department_name {
        padding: 5px 9px;
        padding-right: 30px;
        color: #fff;
        font-size: 12px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        text-align-last: left;
      }
      .selece_icon {
        position: absolute;
        top: 50%;
        right: 8px;
        margin-top: -6px;
        transition: transform 0.3s ease-in-out;
        transform-origin: 50% 50%;
      }
    }
    .dep_box {
      position: absolute;
      left: 16px;
      right: 16px;
      bottom: -255px;
      padding-right: 16px;
      background: rgba(255, 255, 255, 0.9);
      border-radius: 4px;
      height: 250px;
      overflow-y: scroll;
      z-index: 9999999;
      -webkit-overflow-scrolling: touch;
    }
    .toggle {
      outline: none;
      border: none;
      background: inherit;
      font-size: 14px;
      color: #fff;
      .btn_icon {
        margin-top: -5px;
      }
    }
  }
}
.vux-circle-demo {
  padding-top: 20px;
  text-align: center;
  /*background: rgba(0,0,0,0.3);*/
}

.vux-circle-demo > div {
  margin: 0 auto;
}
</style>
<style lang="less">
.mainManage {
  width: 100%;
  height: 100%;
  position: relative;
}

.mainManage .text1 {
  font-size: 16px;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  color: rgba(255, 255, 255, 1);
  margin-top: 2px;
}

.mainManage .homeBackground {
  background: url("../../assets/icon/bg.png");
  background-size: 100% 100%;
}

.mainManage .homeBackground .tuHome {
  width: 34px;
  height: 34px;
  border-radius: 4em;
  background: rgb(34, 35, 63);
  float: right;
  margin: 10px 10px;
  border: 1px #456de6 solid;
  opacity: 0.8;
}
</style>
